package model

import (
	"blog/errmsg"
	"github.com/jinzhu/gorm"
)

type Article struct {
	gorm.Model
	Category ArticleCategory `gorm:"foreignkey:Cid" json:"category"`
	Title string `gorm:"type:varchar(100);not null" json:"title"`
	Cid int `gorm:"type:int;not null" json:"cid"`
	Desc string `gorm:"type:varchar(200)" json:"desc"`
	Content string `gorm:"type:longtext" json:"content"`
	Img string `gorm:"type:varchar(100)" json:"img"`
}

func (this *Article)CreateArt()(code int,msg string){
	if err := db.Create(this).Error;err!=nil{
		return errmsg.FAIL,err.Error()
	}
	return errmsg.SUCCESS,""
}
func (this *Article)GetArt(id int)(code int,msg string,article interface{}){
	var art Article
	if err :=db.Preload("Category").Where("id = ?",id).First(&art).Error;err!=nil{
		return errmsg.FAIL,err.Error(),nil
	}
	return errmsg.SUCCESS,"",art
}
func (this *Article)GetArts(page,pagesize int)(code int,msg string,articles []Article,tl int){
	var arts []Article
	var total int
	fdb := db.Preload("Category").Limit(pagesize).Offset((page-1)*pagesize).Find(&arts).Count(&total)
	if fdb.Error !=nil && fdb.Error!=gorm.ErrRecordNotFound{
		return errmsg.FAIL,fdb.Error.Error(),nil,0
	}
	return errmsg.SUCCESS,"",arts,total
}
func (this *Article)GetArtsByCateId(cid int,page,pagesize int)(code int,msg string,articles []Article){
	var arts []Article
	fdb := db.Preload("Category").Limit(pagesize).Offset((page-1)*pagesize).Where("cid = ?",cid).Find(&arts)
	if fdb.Error !=nil && fdb.Error!=gorm.ErrRecordNotFound{
		return errmsg.FAIL,fdb.Error.Error(),nil
	}
	if fdb.RowsAffected == 0{
		return errmsg.FAIL,"该分类文章不存在",nil
	}
	return errmsg.SUCCESS,"",arts
}
func (this Article)UpdateArt()(int,string){
	maps:=make(map[string]interface{})
	maps["title"] = this.Title
	maps["cid"] = this.Cid
	maps["desc"] = this.Desc
	maps["content"] = this.Content
	maps["img"] = this.Img
	udb := db.Model(&Article{}).Where("id = ?",this.ID).Updates(maps)
	if err:=udb.Error;err!=nil{
		return errmsg.FAIL,err.Error()
	}
	if  udb.RowsAffected == 0{
		return errmsg.FAIL,"无此记录"
	}
	return errmsg.SUCCESS,""
}
func (this *Article)DeleteArt(id int)(code int,msg string){
	ddbn := db.Where("id = ?",id).Delete(&Article{})
	if err:=ddbn.Error;err!=nil{
		return errmsg.FAIL,err.Error()
	}
	if ddbn.RowsAffected == 0{
		return errmsg.FAIL,"无此记录"
	}
	return errmsg.SUCCESS,""
}